package com.itqian.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;
import java.util.Set;

/**
 * @author shishuqian
 * date 2021/12/6
 * time 17:07
 **/
public class JWTUtils {

    /**
     * 密钥
     */
    private static final String SIGN = "fd#FVH45Dfbdm*%Fdvf87";

    /**
     * token时间，默认7天
     */
    private static final Calendar EXPIRE = Calendar.getInstance();
    static {
        EXPIRE.add(Calendar.DATE,7);
    }

    /**
     * 生成token
     */
    public static String getToken(Map<String, String> map){

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //设置payload
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries){
            builder.withClaim(entry.getKey(),entry.getValue());
        }

        //设置token的过期时间,sign
        String token = builder.withExpiresAt(EXPIRE.getTime())
                .sign(Algorithm.HMAC256(SIGN));

        return token;
    }

    /**
     * 校验token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取token中的信息
     */
    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

}
